#include "../common.h"

static void parseSubjectAltName(const STACK_OF(GENERAL_NAME) *subjectAltName);

int main(int argc, char* argv[])
{
    X509 *cert;
    X509_EXTENSION *ext;
    int ext_index;

    // 从文件中加载证书
    FILE *cert_file = fopen("/home/ts/document/zhb/ca/user01.pem", "r");
    cert = PEM_read_X509(cert_file, NULL, NULL, NULL);
    fclose(cert_file);
	
    STACK_OF(GENERAL_NAME) *subjectAltName = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
	if(NULL != subjectAltName) {
		printf("subjectAltName is not NULL, at line %d.\n", __LINE__);
		parseSubjectAltName(subjectAltName);
	}
	else
	{
		printf("subjectAltName is not NULL, at line %d.\n", __LINE__);
		return -1;
	}

	return 0;
}

static void parseSubjectAltName(const STACK_OF(GENERAL_NAME) *subjectAltName)
{
	int32_t size = 0;
	if(NULL == subjectAltName) {
		return;
	}
	
	size = sk_GENERAL_NAME_num(subjectAltName);
	printf("subjectAltName size = %d, at line %d.\n", size, __LINE__);
	
	for (int32_t index = 0; index < size; ++index)
	{
	    GENERAL_NAME *general = sk_GENERAL_NAME_value(subjectAltName, index);
		int type = general->type;
		printf("subjectAltName type = %d, at line %d.\n", type, __LINE__);
		switch (type)
	    {
			case GEN_X400:
				break;
			case GEN_EDIPARTY:
				break;
			case GEN_OTHERNAME:
				break;
			case GEN_EMAIL:
			case GEN_DNS:
			case GEN_URI:
			{			
  				printf("length=%d,at line %d.\n", general->d.ia5->length, __LINE__);
				printf("GEN_EMAIL/GEN_DNS/GEN_URI:%s,at line %d.\n", general->d.ia5->data, __LINE__);
				break;
			}
			case GEN_DIRNAME:
				break;
			case GEN_IPADD:
			{
  				printf("length=%d,at line %d.\n", general->d.ia5->length, __LINE__);
				printf("GEN_IPADD:%d:%d:%d:%d,at line %d.\n", 
					general->d.ia5->data[0],general->d.ia5->data[1],
					general->d.ia5->data[2],general->d.ia5->data[3],__LINE__);
				break;
			}
			case GEN_RID:
				break;
	   }
	}
}

